package com.lxk.controller.admin;

import com.lxk.common.Constant;
import com.lxk.domain.BlogDbEntity;
import com.lxk.domain.dto.BlogInfoDto;
import com.lxk.domain.dto.BlogQueryDto;
import com.lxk.domain.dto.PageInfo;
import com.lxk.domain.vo.IndexBlogVo;
import com.lxk.service.BlogService;
import com.lxk.service.TagService;
import com.lxk.service.TypeService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;

import static com.lxk.common.Constant.BConstants.YN_INVALID;

/**
 * Created by Lxk on 2020/6/14.
 */
@Controller
@RequestMapping("/admin")
public class BBlogController {

    private static Logger logger = LoggerFactory.getLogger(BBlogController.class);

    @Resource
    private BlogService blogService;

    @Resource
    private TypeService typeService;

    @Resource
    private TagService tagService;

    @GetMapping("/blogs")
    public String blogs(PageInfo<BlogQueryDto,BlogDbEntity> pageInfo,BlogQueryDto queryDto, Model model){
        pageInfo.setQueryDto(queryDto);
        blogService.buildPageInfo(pageInfo);
        model.addAttribute("page",pageInfo);
        return "/admin/blogs";
    }

    @PostMapping("/blogs/query")
    public String query(PageInfo<BlogQueryDto,BlogDbEntity> pageInfo, BlogQueryDto queryDto, Model model){
        pageInfo.setQueryDto(queryDto);
        blogService.buildPageInfo(pageInfo);
        model.addAttribute("page",pageInfo);
        return "/admin/blogs :: blogList";
    }

    @GetMapping("/blogs/input/{id}")
    public String input(@PathVariable String id, Model model){
        logger.info("blogs input id:{}",id);
        if(!Constant.BConstants.NULL_VAL.equals(id)){
            IndexBlogVo vo = blogService.queryById(id);
            model.addAttribute("blog",vo);
        }
        model.addAttribute("types",typeService.listAll());
        model.addAttribute("tags",tagService.listAll());
        return "/admin/blogs-input";
    }

    @GetMapping("/blogs/delete/{id}")
    public String delete(@PathVariable String id,Model model){
        blogService.deleteBlog(Long.parseLong(id));
        //todo blog_tag_rel是否要删除
        return "redirect:/admin/blogs";
    }

    @PostMapping("/blogs/add")
    public String add(BlogInfoDto blogInfoDto){
        logger.info("request blog content:{}",blogInfoDto);
        blogService.saveBlog(blogInfoDto);
        return "redirect:/admin/blogs";
    }

}
